<template>
  <div>
    <el-form
      :inline="true"
      :model="formInline"
      class="demo-form-inline"
      size="small"
    >
      <el-form-item label="EXCEL文件路径：">
        <el-input
          v-model="formInline.demand"
          readonly
          placeholder="请选择文件"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <form id="fileForm">
          <input
            type="file"
            ref="fileUpload"
            name="file"
            accept=".xls, .xlsx"
            style="display: none"
            @change="uploadFileChange"
          />
          <el-button type="primary" @click="selectWjButton">浏览</el-button>
          <el-button
            type="primary"
            @click="jxExcelFile"
            :disabled="formInline.demand === ''"
            >解析文件</el-button
          >
        </form>
      </el-form-item>
      <el-form-item style="float: right;">
        <el-button size="small" type="primary" @click="displayCoordinates"
          >显示坐标</el-button
        >
        <el-button type="primary" @click="OpenAddModal">添加</el-button>
      </el-form-item>
    </el-form>
    <main class="table_container">
      <div :key="jxTableKey">
        <el-table
          :data="jxInputData"
          style="width: 100%; overflow: auto"
          :row-class-name="iconHadler"
          v-loading="jxTableLoading"
          stripe
          class="mainTable"
          height="380"
        >
          <el-table-column label="序号" width="80" type="index" />
          <el-table-column show-overflow-tooltip label="目标编号" prop="mbbh" />
          <el-table-column show-overflow-tooltip label="经度" prop="pointJd" />
          <el-table-column show-overflow-tooltip label="纬度" prop="pointWd" />

          <el-table-column label="操作">
            <template slot-scope="scope">
              <span
                class="operation"
                type="primary"
                @click="handleRemoveXq(scope.row, scope.$index)"
                >删除</span
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </main>

    <el-dialog append-to-body title="需求录入" :visible.sync="enterVisible">
      <el-form
        inline
        :model="enterForm"
        :rules="enterRules"
        ref="enterForm"
        label-width="100px"
      >
        <el-form-item label="目标编号" prop="mbbh">
          <el-input v-model="enterForm.mbbh" />
        </el-form-item>
        <el-form-item label="经度" prop="pointJd">
          <el-input v-model="enterForm.pointJd" />
        </el-form-item>
        <el-form-item label="纬度" prop="pointWd">
          <el-input v-model="enterForm.pointWd" />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addXq('enterForm')">确定</el-button>
        <el-button @click="cancel('enterForm')">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { UploadExcel } from '@/api/taskPlanning/index'
export default {
  props: {
    callbackTable: {
      type: Function,
      default: () => {}
    }
  },
  data() {
    return {
      jxTableLoading: false,
      formInline: {
        demand: ''
      },
      jxInputData: [],
      jxTableKey: 0,
      currentPage: 1,
      pageSize: 10,
      allData: [],
      enterVisible: false,
      enterForm: {
        mbbh: '',
        pointJd: '',
        pointWd: ''
      },
      enterRules: {
        mbbh: [{ required: true, message: '请输入目标编号', trigger: 'blur' }],
        pointJd: [
          { required: true, message: '请输入经度', trigger: 'blur' },
          {
            validator: this.jdCoolarInfo,
            message: '经度格式不正确',
            trigger: 'blur'
          }
        ],
        pointWd: [
          { required: true, message: '请输入纬度', trigger: 'blur' },
          {
            validator: this.wdCoolarInfo,
            message: '纬度格式不正确',
            trigger: 'blur'
          }
        ]
      },
      isShowCor: false,
      fileRef: undefined
    }
  },
  methods: {
    loadTable() {
      this.currentPage++
      this.jxInputData = this.jxInputData.concat(
        this.paginate(this.allData, this.currentPage, this.pageSize)
      )
    },
    // 分页函数
    paginate(items, pageNumber, pageSize) {
      // 计算当前页应该开始的索引
      const startIndex = (pageNumber - 1) * pageSize

      // 使用slice截取当前页的数据
      return items.slice(startIndex, startIndex + pageSize)
    },
    // 解析excel文件
    jxExcelFile() {
      this.jxTableLoading = true
      const fileInput = this.fileRef
      if (fileInput.files.length > 0) {
        const file = fileInput.files[0]
        const formData = new FormData()
        formData.append('file', file)
        formData.append('type', '1')
        UploadExcel(formData).then(res => {
          if (res.data.code === 200) {
            const data = res.data
            this.jxInputData = data.data
            this.$emit('callbackTable', this.jxInputData)

            // 如果后期需要分页，可以把下面的代码解除注释
            // this.allData = data.data
            // this.jxInputData = this.paginate(
            //   this.allData,
            //   this.currentPage,
            //   this.pageSize
            // )
            this.jxTableKey = Math.random()
            this.jxTableLoading = false
            fileInput.remove() // 上传完成后，删除这个DOM元素
          }
        })
      }
    },

    // 监听上传的回调
    uploadFileChange(event) {
      let that = this
      if (event.target.files.length > 0) {
        const file = event.target.files[0]
        that.formInline.demand = file.name
      }
    },
    // 选择需要上传的文件
    selectWjButton() {
      if(this.fileRef){
        this.fileRef.remove() // 上传完成后，删除这个DOM元素
      }
      let that = this
      // 创建一个input标签
      that.fileRef = document.createElement('input')
      // 设置input标签的属性
      that.fileRef.name = 'file'
      // 设置input标签的样式
      that.fileRef.type = 'file'
      // 设置input标签的属性
      that.fileRef.accept = '.xls,.xlsx'
      // 设置input标签的样式
      that.fileRef.style.display = 'none'
      // 将input标签添加到body中
      that.fileRef.click()
      document.body.appendChild(that.fileRef)
      // 监听用户选择文件后的操作
      that.fileRef.addEventListener('change',that.uploadFileChange, false)
    },

    iconHadler({ row }) {
      if (!row.jcybList || row.jcybList.length == 0) {
        return 'icon-no'
      }
    },

    /** 经度校验 */
    jdCoolarInfo(rule, value, callback) {
      const coordinateRegex = /^[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/
      if (coordinateRegex.test(value)) {
        callback()
      } else {
        callback(new Error('经度格式不正确'))
      }
    },

    /** 纬度校验 */
    wdCoolarInfo(rule, value, callback) {
      const coordinateRegex = /^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?)$/
      if (coordinateRegex.test(value)) {
        callback()
      } else {
        callback(new Error('经度格式不正确'))
      }
    },

    /** 删除单行数据 */
    handleRemoveXq(row, index) {
      this.jxInputData.splice(index, 1)
    },
    /** 打开弹窗 */
    OpenAddModal() {
      this.enterForm = {
        mbbh: '',
        pointJd: '',
        pointWd: ''
      }
      this.enterVisible = true
    },

    /** 确定 */
    addXq(formName) {
      this.$refs[formName].validate(valid => {
        if (!valid) return false
        this.jxInputData.push(this.enterForm)
        this.enterVisible = false
      })
    },

    /** 取消 */
    cancel(formName) {
      this.$refs[formName].resetFields()
      this.enterVisible = false
    },

    /** 显示坐标 */
    displayCoordinates() {
      this.isShowCor = !this.isShowCor
      const handleData = this.jxInputData.map(item => {
        return {
          longitude: parseFloat(item.pointJd),
          latitude: parseFloat(item.pointWd)
        }
      })

      // 在此调用cesium的方法
      this.$bus.$emit('renderPoint', handleData,this.isShowCor)
    }
  }
}
</script>

<style></style>
